import React, { PureComponent } from 'react';
import IceContainer from '@icedesign/container';
import { Input, Table, Message, Button, Grid } from '@alifd/next';
import styles from './index.module.scss';
import request from '../../../../utils/request';
import { host } from '../../../../const';
import classnames from 'classnames';
import './index.scss';
import MMap from '@/components/mMap';
import NImg from '@/components/nImg';
import WebStorageCache from 'web-storage-cache';

const wsCache = new WebStorageCache();
const { Col, Row } = Grid;


export default class Index extends PureComponent {
  static displayName = 'Index';

  static propTypes = {};

  static defaultProps = {};


  constructor(props) {
      super(props);
      this.index = 1;
      this.battleId = window.location.href.split('/')[6];
      this.mapType = wsCache.get('mapTyeForReplay');
      this.state = {
          mapBase64: {},
          log: '',
          indexInfo: '',
          redVestStatisticsStr: '',
          blueVestStatisticsStr: '',
          redVestList: [],
          blueVestList: [],
      };
      this.totIndex = 1;
      this.isAutoPlay = false;
      this.timerID = null;
      this.getBattleRepalyData();
  }

  componentWillUnmount() {
      wsCache.set('mapTyeForReplay', '');
      if (this.timerID != null) {
          clearInterval(this.timerID);
      }
  }


  getBattleRepalyData = () => {
      request({
          method: 'GET',
          url: `${host}/battle/record/${this.battleId}/${this.index}`,
      }).then((res) => {
          let point = [];
          let zoom = 10;
          const data = res?.data?.data;
          const code = res?.data?.code;
          if (code === 200) {
              this.totIndex = data.totIndex;
              const mapEntity = data?.mapEntity;
              this.state.mapBase64 = data.mapBase64;
              let appendLog = '';
              if (data.logList != null) {
                  data.logList.forEach((log) => {
                      appendLog = `${appendLog + log.time}      ${log.log}\n`;
                  });
              }
              this.state.log = appendLog;

              this.state.redVestList = [];
              this.state.blueVestList = [];
              this.state.orangeVestList = [];
              this.state.yellowVestList = [];
              const redVestStatistics = new Array(0, 0, 0, 0, 0);
              const blueVestStatistics = new Array(0, 0, 0, 0, 0);
              const orangeVestStatistics = new Array(0, 0, 0, 0, 0);
              const yellowVestStatistics = new Array(0, 0, 0, 0, 0);
              const arr = [];
              data.battleRecordEntity.vestData.forEach((vest) => {
                  let now;
                  vest.id = vest.num;
                  arr.push(vest);
                  if (vest.team == 'red') {
                      now = redVestStatistics;
                      this.state.redVestList.push(vest);
                  } else if (vest.team == 'blue') {
                      now = blueVestStatistics;
                      this.state.blueVestList.push(vest);
                  } else if (vest.team == 'orange') {
                      now = orangeVestStatistics;
                      this.state.orangeVestList.push(vest);
                  } else if (vest.team == 'yellow') {
                      now = yellowVestStatistics;
                      this.state.yellowVestList.push(vest);
                  }
                  if (vest.status == 0) {
                      return true;
                  }
                  now[vest.hp / 25] = now[vest.hp / 25] + 1;
              });
              this.state.redVestStatisticsStr = `${'红方\n' + '正常：'}${redVestStatistics[4]}\n` + `轻伤：${redVestStatistics[3]}\n` + `中伤：${redVestStatistics[2]}\n` + `重伤：${redVestStatistics[1]}\n` + `阵亡：${redVestStatistics[0]}\n`;
              this.state.blueVestStatisticsStr = `${'蓝方\n' + '正常：'}${blueVestStatistics[4]}\n` + `轻伤：${blueVestStatistics[3]}\n` + `中伤：${blueVestStatistics[2]}\n` + `重伤：${blueVestStatistics[1]}\n` + `阵亡：${blueVestStatistics[0]}\n`;
              this.state.orangeVestStatisticsStr = `${'人质\n' + '正常：'}${orangeVestStatistics[4]}\n` + `轻伤：${orangeVestStatistics[3]}\n` + `中伤：${orangeVestStatistics[2]}\n` + `重伤：${orangeVestStatistics[1]}\n` + `阵亡：${orangeVestStatistics[0]}\n`;
              this.state.yellowVestStatisticsStr = `${'绑匪\n' + '正常：'}${yellowVestStatistics[4]}\n` + `轻伤：${yellowVestStatistics[3]}\n` + `中伤：${yellowVestStatistics[2]}\n` + `重伤：${yellowVestStatistics[1]}\n` + `阵亡：${yellowVestStatistics[0]}\n`;
              if (mapEntity) {
                  point = [mapEntity.lng, mapEntity.lat];
                  zoom = mapEntity.zoom;
              }


              this.setState({
                  indexInfo: `本次演习共有${this.totIndex}条记录，当前正在展示第${this.index}条，当前记录时间为${data.battleRecordEntity.time}`,
                  point,
                  zoom,
              });
              if (this.refs.myref) {
                  this.refs.myref.drarPoint(arr);
              }
          }
      });
  }

  nextRecord = () => {
      if (this.index + 1 <= this.totIndex) {
          this.index++;
          this.getBattleRepalyData();
      } else {
          Message.error('本次演习回放已播放完毕');
          if (this.isAutoPlay) {
              this.pauseAutoPlay();
          }
      }
  }

  lastRecord = () => {
      if (this.index != 1) {
          this.index--;
          this.getBattleRepalyData();
      } else {
          Message.error('当前演习记录是第一张，无法回退。');
      }
  }

  renderStatus = (value, index, record) => {
      if (record.status == 0) {
          return <a style={{ color: 'red' }}>离线</a>;
      }
      if (record.hp > 0) {
          return <a style={{ color: 'green' }}>正常</a>;
      }
      if (record.hp == 0) {
          return <a style={{ color: 'red' }}>阵亡</a>;
      }
  }

  startAutoPlay = () => {
      this.isAutoPlay = true;

      const ajaxTime = wsCache.get('ajaxTime') ? Number(wsCache.get('ajaxTime')) : 5000;
      this.timerID = setInterval(() => {
          this.nextRecord();
      }, ajaxTime);

      Message.success('开始自动回放');
      this.forceUpdate();
  }

  pauseAutoPlay = () => {
      this.isAutoPlay = false;
      if (this.timerID != null) {
          clearInterval(this.timerID);
      }
      Message.success('停止自动回放');
      this.forceUpdate();
  }

  render() {
      return (

          <IceContainer className={classnames('lite-table', styles.wrap)}>


              <Row >
                  <Col span={24}> <div style={{ width: '100%', height: '50vh', maxWidth: 'calc(100vw - 60px - 200px)' }} className={styles.itemWrap} >

                      {
                          Number(this.mapType) === 1 ? <NImg mapBase64={this.state.mapBase64} showFullButton /> : this.state.point && this.state.point.length ?
                              <MMap isShowCenter ref="myref" defaultCenter={this.state.point} defaultZoom={this.state.zoom} />
                              : null
                      }


                  </div>
                  </Col>
              </Row>
              <Row >
                  <Col span={24}>     <div style={{ width: '100%', height: '100%' }} className={styles.itemWrap} >
                      <div style={{
                          width: '100%', height: '100%', display: 'flex', flexDirection: 'column',
                      }}
                      >
                          <div className="title" style={{ display: 'flex', justifyContent: 'center', flex: '1' }}>

                              <Input.TextArea style={{ height: '100%', width: '50%' }} rows={6} value={this.state.log} />    &nbsp;
                              <Input.TextArea style={{ height: '100%', width: '10%' }} rows={6} value={this.state.redVestStatisticsStr} /> &nbsp;
                              <Input.TextArea style={{ height: '100%', width: '10%' }} rows={6} value={this.state.blueVestStatisticsStr} />     &nbsp;
                              <Input.TextArea style={{ height: '100%', width: '10%' }} rows={6} value={this.state.orangeVestStatisticsStr} /> &nbsp;
                              <Input.TextArea style={{ height: '100%', width: '10%' }} rows={6} value={this.state.yellowVestStatisticsStr} />
                          </div>
                          <div className="title" style={{ display: 'flex', justifyContent: 'center' }}>
                              <Button type="normal" onClick={this.lastRecord}>上一条记录</Button>
                              <Button type="normal" onClick={this.nextRecord}>下一条记录</Button>
                              <Button type="normal" onClick={this.startAutoPlay} disabled={this.isAutoPlay}>开始自动回放</Button>
                              <Button type="normal" onClick={this.pauseAutoPlay} disabled={!this.isAutoPlay}>暂停自动回放</Button>
                          </div>
                          <div className="title" style={{ display: 'flex', justifyContent: 'center' }}>
                              {this.state.indexInfo}
                          </div>
                      </div>

                  </div>

                  </Col>
              </Row>
              <Row >
                  <Col span={24} >
                      <div style={{ height: '100%' }} >
                          <div style={{ width: '100%' }} className={styles.itemWrap} >
                              <h1 style={{ color: 'red' }}>红方</h1>
                              <Table dataSource={this.state.redVestList} hasBorder={false}>
                                  <Table.Column title="编号" dataIndex="num" />
                                  <Table.Column title="主武器" dataIndex="weapon1" />
                                  <Table.Column title="主武器弹药量" dataIndex="ammo1" />
                                  <Table.Column title="副武器" dataIndex="weapon2" />
                                  <Table.Column title="副武器弹药量" dataIndex="ammo2" />
                                  <Table.Column title="生命值" dataIndex="hp" />
                                  <Table.Column title="状态" cell={this.renderStatus} />
                              </Table>
                          </div>
                          <div style={{ width: '100%' }} className={styles.itemWrap} >
                              <h1 style={{ color: 'blue' }}>蓝方</h1>
                              <Table dataSource={this.state.blueVestList} hasBorder={false}>
                                  <Table.Column title="编号" dataIndex="num" />
                                  <Table.Column title="主武器" dataIndex="weapon1" />
                                  <Table.Column title="主武器弹药量" dataIndex="ammo1" />
                                  <Table.Column title="副武器" dataIndex="weapon2" />
                                  <Table.Column title="副武器弹药量" dataIndex="ammo2" />
                                  <Table.Column title="生命值" dataIndex="hp" />
                                  <Table.Column title="状态" cell={this.renderStatus} />
                              </Table>

                          </div>
                          <div style={{ width: '100%' }} className={styles.itemWrap} >
                              <h1 style={{ color: 'orange' }}>人质</h1>
                              <Table dataSource={this.state.orangeVestList} hasBorder={false}>
                                  <Table.Column title="编号" dataIndex="num" />
                                  <Table.Column title="主武器" dataIndex="weapon1" />
                                  <Table.Column title="主武器弹药量" dataIndex="ammo1" />
                                  <Table.Column title="副武器" dataIndex="weapon2" />
                                  <Table.Column title="副武器弹药量" dataIndex="ammo2" />
                                  <Table.Column title="生命值" dataIndex="hp" />
                                  <Table.Column title="状态" cell={this.renderStatus} />
                              </Table>
                          </div>
                          <div style={{ width: '100%' }} className={styles.itemWrap} >
                              <h1 style={{ color: 'brown' }}>劫匪</h1>
                              <Table dataSource={this.state.yellowVestList} hasBorder={false}>
                                  <Table.Column title="编号" dataIndex="num" />
                                  <Table.Column title="主武器" dataIndex="weapon1" />
                                  <Table.Column title="主武器弹药量" dataIndex="ammo1" />
                                  <Table.Column title="副武器" dataIndex="weapon2" />
                                  <Table.Column title="副武器弹药量" dataIndex="ammo2" />
                                  <Table.Column title="生命值" dataIndex="hp" />
                                  <Table.Column title="状态" cell={this.renderStatus} />
                              </Table>
                          </div>

                      </div>
                  </Col>
              </Row>


          </IceContainer>


      );
  }
}
